<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import {
  ElMessage,
  ElForm,
  ElFormItem,
  ElInput,
  ElUpload,
  ElButton,
  ElMessageBox,
  ElImage,
  ElSwitch
} from "element-plus";
import { getSysGroupConfigsApi, setSysGroupConfigsApi } from '@/api/configs/sysConfig';


const configGroupName = "base";

// 定义私有化配置类型
interface BaseConfigModel {
  allowAutoFindDevice: boolean;
}

const formRef = ref<InstanceType<typeof ElForm>>();

// 初始化表单数据
const formData = reactive<{
  groupName: string;
  config: BaseConfigModel;
  updatedAt: string;
}>({
  groupName: configGroupName,
  config: {
    allowAutoFindDevice: false,
  },
  updatedAt: ''
});


// 初始化数据
onMounted(() => {
  // 获取系统私有化配置
  getSysGroupConfigsApi({
    groupName: formData.groupName
  }).then(res => {
    if (res.code === 0 && res.data?.configs) {
      formData.updatedAt = res.data.updatedAt || '';
      try {
        // 解析配置数据
        const configMap: Record<string, any> = {};
        res.data.configs.forEach(item => {
          configMap[item.configKey] = item.configValue;
        });

        // 填充表单数据
        formData.config = {
          allowAutoFindDevice: configMap.allowAutoFindDevice || false,
        };
      } catch (e) {
        console.error('解析配置数据失败', e);
      }
    }
  });
});

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    const submitData = {
      groupName: formData.groupName,
      configs: [
        { configKey: 'allowAutoFindDevice', configValue: formData.config.allowAutoFindDevice, configDesc: '自动发现设备' },
      ]
    };
    ElMessageBox.confirm(
      '确定要保存当前系统基础信息吗？',
      '确认提交',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    ).then(async () => {
      await setSysGroupConfigsApi(submitData);
      ElMessage.success('保存成功');
    }).catch(() => ElMessage.info('已取消保存'));
  } catch (error) {
    ElMessage.error('表单验证失败，请检查填写内容');
  }
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
};

</script>

<template>
  <el-form ref="formRef" :model="formData" label-width="160px" class="form-container">
    <el-form-item label="配置组名" prop="groupName">
      <el-input v-model="formData.groupName" disabled />
    </el-form-item>

    <!-- 允许主动发现设备 -->
    <el-form-item label="允许主动发现设备" prop="configs.allowAutoFindDevice">
      <el-switch
        v-model="formData.config.allowAutoFindDevice"
        :active-value="'true'"
        :inactive-value="'false'"
      />
      <div class="form-hint">提示：开启后服务器不再校验设备编号</div>
    </el-form-item>


    <!-- 更新时间显示 -->
    <el-form-item label="更新时间" v-if="formData.updatedAt">
      <el-input v-model="formData.updatedAt" disabled placeholder="暂无更新时间" />
    </el-form-item>

    <el-form-item class="form-actions">
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.form-container { max-width: 800px; margin: 20px auto; padding: 20px; }
.form-actions { display: flex; justify-content: center; gap: 10px; margin-top: 30px; }
.avatar-uploader .avatar { width: 200px; height: 80px; display: block; }
.upload-slot { width: 200px; height: 80px; border: 1px dashed #d9d9d9; border-radius: 6px; display: flex; flex-direction: column; align-items: center; justify-content: center; cursor: pointer; transition: border-color 0.3s; }
.upload-slot:hover { border-color: #409eff; }
.upload-tip { margin-top: 10px; color: #606266; font-size: 12px; }
.remove-btn { margin-top: 10px; color: #f56c6c; padding: 0; }
.form-hint {
  color: #606266;
  font-size: 12px;
  margin-top: 5px;
}
</style>

